package com.sneaker.shower.service.impl;

import com.sneaker.shower.common.BizException;
import com.sneaker.shower.entity.dto.WxAuthorizeReqDTO;
import com.sneaker.shower.entity.dto.WxCommonReqDTO;
import com.sneaker.shower.service.WxMpPortalService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class WxMpPortalServiceImpl implements WxMpPortalService {

    private final WxMpService wxMpService;
    @Value("${loginPage}")
    private String LOGIN_PAGE;

    public WxMpPortalServiceImpl(WxMpService wxMpService) {
        this.wxMpService = wxMpService;
    }

    @Override
    public String verify(WxCommonReqDTO wxCommonReqDTO) {
        if (StringUtils.isAnyBlank(wxCommonReqDTO.getSignature(), wxCommonReqDTO.getEchostr(), wxCommonReqDTO.getNonce(), wxCommonReqDTO.getTimestamp())) {
            throw new IllegalArgumentException("请求参数非法，请核实！");
        }
        if (wxMpService.checkSignature(wxCommonReqDTO.getTimestamp(), wxCommonReqDTO.getNonce(), wxCommonReqDTO.getSignature())) {
            log.info("微信验证通过");
            return wxCommonReqDTO.getEchostr();
        }
        throw new IllegalArgumentException("非法请求参数，请核实！");
    }

    @Override
    public String handleMsg(String body, WxCommonReqDTO wxCommonReqDTO) {
        if (!wxMpService.checkSignature(wxCommonReqDTO.getTimestamp(), wxCommonReqDTO.getNonce(), wxCommonReqDTO.getSignature())) {
            log.info("非法请求");
            return "success";
        }
        String out = null;
        WxMpXmlOutNewsMessage outNewsMessage = new WxMpXmlOutNewsMessage();
        outNewsMessage.setMsgType(WxConsts.XmlMsgType.NEWS);
        outNewsMessage.setArticleCount(1);
        outNewsMessage.setCreateTime(System.currentTimeMillis());
        WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
        item.setPicUrl("https://sneakershower.club/gateway/file/download?file=5d4b0afb61924d43bc43e76ef678cc33.png");
        item.setDescription("球鞋澡堂客服入口");
        item.setTitle("球鞋澡堂客服入口");
        item.setUrl("https://w.url.cn/s/A2p7qdM");
        outNewsMessage.addArticle(item);
        if (StringUtils.isEmpty(wxCommonReqDTO.getEncrypt_type())) {            // 明文传输的消息
            log.info("明文模式处理");
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(body);
            if (!Objects.equals(inMessage.getMsgType(), WxConsts.XmlMsgType.TEXT) || !Objects.equals(inMessage.getContent(), "客服入口")) {
                return "success";
            }
            outNewsMessage.setToUserName(inMessage.getFromUser());
            outNewsMessage.setFromUserName(inMessage.getToUser());
            out = outNewsMessage.toXml();
        } else if ("aes".equalsIgnoreCase(wxCommonReqDTO.getEncrypt_type())) {
            log.info("安全模式处理");
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(body, wxMpService.getWxMpConfigStorage(),
                    wxCommonReqDTO.getTimestamp(), wxCommonReqDTO.getNonce(), wxCommonReqDTO.getMsg_signature());
            log.info("\n消息解密后内容为：\n{} ", inMessage.toString());
            if (!Objects.equals(inMessage.getMsgType(), WxConsts.XmlMsgType.TEXT) || !Objects.equals(inMessage.getContent(), "客服入口")) {
                return "success";
            }
            outNewsMessage.setToUserName(inMessage.getFromUser());
            outNewsMessage.setFromUserName(inMessage.getToUser());
            out = outNewsMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }
        log.info("\n组装回复信息：{}", out);
        return out;
    }

    @Override
    public String jump(WxAuthorizeReqDTO wxAuthorizeReqDTO) {
        try {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(wxAuthorizeReqDTO.getCode());
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            return String.format(LOGIN_PAGE, wxMpUser.getOpenId());
        } catch (WxErrorException e) {
            log.error("~" + e);
            throw new BizException("服务器异常");
        }
    }

}
